/*---------------------------------------------------------------------------

  NAME:
    ascii_write
  
  CALLING SEQUENCE:
    IDL> ascii_write, struct, filename, /append, delimiter=, /bracket_arrays, status=

  PURPOSE:

    Write an idlstructure to an ascii file.  This is about 12 times faster than
    using the build in printf statement for small structure definitions.  For
    really big ones, getting the offsets is the bottleneck. For a tsObj file
    its only about 5 times faster.

    This program is written in C and is linked to IDL via the DLM mechanism.

  INPUTS: 
     struct: The structure array to write. 
     file: Filename for output. The user must expand all ~ or other environment variables.  

  OPTIONAL INPUTS:
     delimiter: The delimiter for each field; default is the tab character.
     /append: Append the file.
     /bracket_arrays: {} is placed around array data in each row, with values comma 
        delimited within.  This is the format required for file input to postgresql 
        databases.

  OPTIONAL OUTPUTS:
    status=: The status of the read. 0 for success, 1 for read failure, 
             2 for input errors such as bad file unit.

  TODO:
    Support for file units.  This code is already in ascii_read/binary_read
    so should be straightforward.  Also, use the code in fileio_util to get
    the tag info, etc.
  
  REVISION HISTORY:
    Created December-2005: Erin Sheldon, NYU


  Copyright (C) 2005  Erin Sheldon, NYU.  erin dot sheldon at gmail dot com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


  ---------------------------------------------------------------------------*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "export.h"
#include "fileio_util.h"
#include "ascii_write.h"

KW_RESULT kw;
FILE *OFILEPTR;

void
ascii_write(int argc, IDL_VPTR *argv, char *argk)
{
 
  /* The input variables */
  IDL_VPTR instructVptr;
  IDL_VPTR fileVptr;

  /* What delimter should we use? Default is tab */
  char delim[10];
  char arrDelim[10];

  /* Will we put postgres brackets around the arrays?  Note postgres can only
     read if tab-delimited */
  int bracket_arrays;
  int verbose;
 
  /* Info about the input structure */
  idl_tag_info *tag_info;

  IDL_MEMINT nrows, row;

  /* Loop variables */
  int i;
  int tag, el;

  /* Temporary pointer to hold values */
  UCHAR *tptr;

  /* Failure assumed until we finish */
  aw_set_status(WRITE_FAILURE);

  /********************************************************************
   * Get the keywords and inputs, and process them
   ********************************************************************/

  (void) IDL_KWProcessByOffset(argc, argv, argk, kw_pars, 
			       (IDL_VPTR *) 0, 1, &kw);

  if (aw_nparams(argc) < 2) 
    {
      IDL_Message(IDL_M_NAMED_GENERIC, IDL_MSG_INFO,
		  "-Syntax: ascii_write, struct, file, /append, delimiter=, /bracket_arrays, status=");
      return;
    }

  instructVptr = argv[0];
  fileVptr = argv[1];


  /* We only accept structure variables */
  if (instructVptr->type != IDL_TYP_STRUCT) 
    {
      error_message("Input variable must be a structure",NULL);
      return;
    }
  
  /* Get the file pointer. */
  if ( (kw.append_there) && (kw.append) )
    OFILEPTR = get_fileptr(fileVptr, "a");
  else
    OFILEPTR = get_fileptr(fileVptr, "w");

  if (OFILEPTR==NULL)
    {
      aw_set_status(INPUT_ERROR);      
      return;  
    }


  /* Should we print info? */
  if ( (kw.verbose_there) && (kw.verbose != 0) )
    verbose=1;
  else
    verbose=0;
      

  /* Set the delimiter */
  if (kw.delimiter_there)
    strcpy(delim, IDL_STRING_STR(&kw.delimiter));
  else
    strcpy(delim, "\t");



  /* Should we place brackets around the arrays? */
  if ( (kw.bracket_arrays_there) && (kw.bracket_arrays != 0) )
    {
      bracket_arrays = 1;
      strcpy(arrDelim, ",");
    }
  else 
    {
      bracket_arrays = 0;
      strcpy(arrDelim, delim);
    }

  /* Get info about struct and tags */
  tag_info = get_idl_tag_info(instructVptr, verbose);
  nrows = (IDL_MEMINT) instructVptr->value.s.arr->n_elts;


  /* Now loop over all the structure array elements and print each field */
  for (row=0;row<nrows;row++)
    {
      /* Process The fields */
      for (tag=0;tag<tag_info->ntags;tag++)
	{

	  /* Arrays */
	  if ((tag_info->tagDesc[tag]->flags & IDL_V_ARR) != 0) 
	    {

	      if (bracket_arrays) 
		fprintf(OFILEPTR,"{");

	      for (el=0;el<tag_info->tagNelts[tag];el++)
		{
		  tptr = (instructVptr->value.s.arr->data +
			  row*instructVptr->value.arr->elt_len + 
			  tag_info->tagOffsets[tag] + 
			  el*tag_info->tagDesc[tag]->value.arr->elt_len
			  );
		  aw_print(tag_info->tagDesc[tag]->type, tptr);
		  if (el < tag_info->tagNelts[tag]-1)
		    fprintf(OFILEPTR, arrDelim);

		}
	      if (bracket_arrays) 
		fprintf(OFILEPTR,"}");

	    }
	  else 
	    {
	      tptr = (instructVptr->value.s.arr->data +
		      row*instructVptr->value.arr->elt_len + 
		      tag_info->tagOffsets[tag]
		      );
	      aw_print(tag_info->tagDesc[tag]->type, tptr);
	    }

	  if (tag < tag_info->ntags-1) 
	    fprintf(OFILEPTR, delim);
	  else
	    fprintf(OFILEPTR, "\n");
	  
	} /* tags */
	      
    }

  fflush(OFILEPTR);

  free_tag_info(tag_info);

  if (fileVptr->type == IDL_TYP_STRING)
    fclose(OFILEPTR);

  aw_set_status(WRITE_SUCCESS);
  IDL_KW_FREE;

  return;

}

int
aw_print(int idlType, UCHAR *tptr)
{

  switch(idlType)
    {
    case IDL_TYP_FLOAT: 
      fprintf(OFILEPTR, "%g", *(float *)tptr);
      return(flen); /* number of bytes */
      break;
    case IDL_TYP_DOUBLE:
      fprintf(OFILEPTR, "%15.8e", *(double *)tptr);
      return(dlen);
      break;
    case IDL_TYP_BYTE:
      fprintf(OFILEPTR, "%d", *(short *)tptr);
      return(blen);
      break;
    case IDL_TYP_INT:
      fprintf(OFILEPTR, "%d", *(short *)tptr);
      return(ilen);
      break;
    case IDL_TYP_UINT:
      fprintf(OFILEPTR, "%d", *(unsigned short *)tptr);
      return(uilen);
      break;
    case IDL_TYP_LONG:
      fprintf(OFILEPTR, "%d", *(IDL_LONG *)tptr);
      return(llen);
      break;
    case IDL_TYP_ULONG:
      fprintf(OFILEPTR, "%d", *(IDL_ULONG *)tptr);
      return(ullen);
      break;
    case IDL_TYP_LONG64:
      fprintf(OFILEPTR, "%lld", *(IDL_LONG64 *)tptr);
      return(l64len);
      break;
    case IDL_TYP_ULONG64:
      fprintf(OFILEPTR, "%lld", *(IDL_ULONG64 *)tptr);
      return(ul64len);
      break;
    case IDL_TYP_STRING:
      fprintf(OFILEPTR, "%s", ( (IDL_STRING *)tptr )->s);
      return(slen);
      break;
    default: 
      printf("Unsupported type %d found\n", idlType);
      fflush(stdout);
      break;
    }
}




/*----------------------------------------------------------------------- 
  set the status keyword if it is there 
  -----------------------------------------------------------------------*/

static void
aw_set_status(int statusVal)
{

  if (kw.status_there) {
    /* This frees any existing memory and sets type to INT with value zero */
    IDL_StoreScalarZero(kw.status, IDL_TYP_INT);
    kw.status->value.i = statusVal;
  }

}

/*-----------------------------------------------------------------------
  nParams
  return the number of parameters.  Accounts for keywords
 -----------------------------------------------------------------------*/

int aw_nparams(int argc)
{

  int nKeywords;

  nKeywords =
    kw.append_there + 
    kw.bracket_arrays_there + 
    kw.delimiter_there + 
    kw.status_there +
    kw.verbose_there;

  return 
    argc - nKeywords;
}

#define ARRLEN(arr) (sizeof(arr)/sizeof(arr[0]))

int IDL_Load(void)
{

  /* This must be static. It is a struct. */
  /* The name in strings is the name by which it will be called from IDL and
     MUST BE CAPITALIZED 
     5th parameter will say if it accepts keywords and some other flags 
     For more info see page 325 of external dev. guide */
  static IDL_SYSFUN_DEF2 procedure_addr[] = {
    { (IDL_SYSRTN_GENERIC) ascii_write, "ASCII_WRITE", 
      0, IDL_MAXPARAMS, 
      IDL_SYSFUN_DEF_F_KEYWORDS, 0},
  };

  /* False means it is not a function */
  return IDL_SysRtnAdd(procedure_addr, IDL_FALSE, ARRLEN(procedure_addr));

}
